package com.lsj.appserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/loginTest")
    public String loginTest(){
        System.out.println("开始组装参数");
        MultiValueMap<Object, Object> map = new LinkedMultiValueMap<>();
        map.add("client_id","appService");
        map.add("client_secret","123");
        map.add("grant_type","client_credentials");
        System.out.println("开始请求认证");
        Map<String,String> resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
        System.out.println("请求认证成功");
        String access_token = resp.get("access_token");
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","Bearer "+access_token);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        System.out.println("开始请求资源");
        ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8081/hello", HttpMethod.GET, httpEntity, String.class);
        System.out.println("请求资源成功");
        System.out.println(entity.getBody());
        return entity.getBody();
    }
}
